<template>
  <view class="patrol-performance-container">
    <!-- 页面标题 -->
    <view class="page-header">
      <view class="header-title">巡检绩效看板</view>
    </view>

    <!-- 月份选择器 -->
    <view class="month-selector">
      <view class="selector-header">
        <text class="selector-title">绩效月份</text>
        <picker mode="date" fields="month" :value="selectedMonth" @change="onMonthChange">
          <view class="month-picker">
            <text>{{ formatMonth(selectedMonth) }}</text>
            <image src="/static/icons/arrow-down.svg" class="arrow-icon" />
          </view>
        </picker>
      </view>
    </view>

    <!-- 绩效核心指标 -->
    <view class="performance-metrics">
      <view class="metric-card">
        <text class="metric-value">{{ performanceMetrics.averageScore }}</text>
        <text class="metric-label">组员平均积分</text>
        <text class="metric-change" :class="performanceMetrics.averageScoreChange >= 0 ? 'positive' : 'negative'">
          {{ performanceMetrics.averageScoreChange >= 0 ? '+' : '' }}{{ performanceMetrics.averageScoreChange }}%
        </text>
      </view>
      <view class="metric-card">
        <text class="metric-value">{{ performanceMetrics.estimatedScore }}</text>
        <text class="metric-label">本月预估积分</text>
        <text class="metric-change" :class="performanceMetrics.estimatedScoreChange >= 0 ? 'positive' : 'negative'">
          {{ performanceMetrics.estimatedScoreChange >= 0 ? '+' : '' }}{{ performanceMetrics.estimatedScoreChange }}%
        </text>
      </view>
      <view class="metric-card">
        <text class="metric-value">{{ performanceMetrics.memberCount }}</text>
        <text class="metric-label">组员数量</text>
        <text class="metric-change" :class="performanceMetrics.memberCountChange >= 0 ? 'positive' : 'negative'">
          {{ performanceMetrics.memberCountChange >= 0 ? '+' : '' }}{{ performanceMetrics.memberCountChange }}
        </text>
      </view>
      <view class="metric-card">
        <text class="metric-value">{{ performanceMetrics.completionRate }}%</text>
        <text class="metric-label">任务完成率</text>
        <text class="metric-change" :class="performanceMetrics.completionRateChange >= 0 ? 'positive' : 'negative'">
          {{ performanceMetrics.completionRateChange >= 0 ? '+' : '' }}{{ performanceMetrics.completionRateChange }}%
        </text>
      </view>
    </view>

    <!-- 绩效趋势图表 -->
    <view class="performance-chart">
      <view class="chart-header">
        <text class="chart-title">绩效趋势</text>
        <button class="refresh-btn" @click="refreshPerformanceChart">刷新图表</button>
      </view>
      <view class="chart-content">
        <qiun-data-charts 
          type="column"
          :opts="performanceChartOpts"
          :chartData="performanceChartData"
        />
      </view>
    </view>

    <!-- 组员积分排行榜 -->
    <view class="member-ranking">
      <text class="ranking-header">组员积分排行</text>
      <view class="member-list">
        <view 
          v-for="(member, index) in memberScores" 
          :key="member.id"
          class="member-item"
          @click="viewMemberDetail(member)"
        >
          <view class="rank-badge" :class="getRankClass(index)">
            {{ index + 1 }}
          </view>
          <view class="member-info">
            <text class="member-name">{{ member.name }}</text>
            <text class="member-dept">{{ member.department }}</text>
          </view>
          <view class="member-score">
            <text class="current-score">{{ member.currentScore }}</text>
            <text class="score-change" :class="member.change >= 0 ? 'positive' : 'negative'">
              {{ member.change >= 0 ? '+' : '' }}{{ member.change }}
            </text>
          </view>
        </view>
      </view>
    </view>

    <!-- 积分获取记录 -->
    <view class="score-records">
      <view class="records-header">
        <text class="records-title">积分获取记录</text>
        <button class="filter-btn" @click="showScoreFilter">筛选</button>
      </view>
      <view class="record-list">
        <view 
          v-for="record in scoreRecords" 
          :key="record.id"
          class="record-item"
          @click="viewScoreDetail(record)"
        >
          <view class="record-info">
            <text class="record-action">{{ record.action }}</text>
            <view class="record-details">
              <text class="record-member">{{ record.memberName }}</text>
              <text class="record-location">{{ record.location }}</text>
            </view>
          </view>
          <view class="record-score">
            <text class="score-value" :class="record.score > 0 ? 'positive' : 'negative'">
              {{ record.score > 0 ? '+' : '' }}{{ record.score }}
            </text>
            <text class="record-time">{{ formatDateTime(record.time) }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="isEmpty" class="empty-state">
      <image src="/static/icons/empty.svg" class="empty-icon" />
      <text class="empty-text">暂无数据</text>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-state">
      <text>加载中...</text>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

// 数据定义
const loading = ref(false)
const selectedMonth = ref(new Date().toISOString().slice(0, 7)) // 格式：YYYY-MM

// 绩效核心指标
const performanceMetrics = ref({
  averageScore: 85,
  averageScoreChange: 5.2,
  estimatedScore: 92,
  estimatedScoreChange: 3.8,
  memberCount: 12,
  memberCountChange: 2,
  completionRate: 94,
  completionRateChange: 1.5
})

// 绩效趋势图表数据
const performanceChartData = ref({
  categories: ['第1周', '第2周', '第3周', '第4周'],
  series: [
    {
      name: '平均积分',
      data: [78, 82, 85, 90]
    },
    {
      name: '完成任务数',
      data: [42, 45, 48, 52]
    }
  ]
})

// 图表配置
const performanceChartOpts = ref({
  color: ['#1890FF', '#52C41A'],
  padding: [15, 15, 0, 5],
  legend: {
    show: true,
    position: 'top',
    float: 'right'
  },
  xAxis: {
    disableGrid: true
  },
  yAxis: {
    data: [
      {
        min: 0
      }
    ]
  },
  extra: {
    column: {
      width: 20
    }
  }
})

// 组员积分数据
const memberScores = ref([
  { id: 1, name: '张三', department: '巡检一组', currentScore: 95, change: 8 },
  { id: 2, name: '李四', department: '巡检二组', currentScore: 92, change: 5 },
  { id: 3, name: '王五', department: '巡检一组', currentScore: 88, change: 3 },
  { id: 4, name: '赵六', department: '巡检三组', currentScore: 85, change: -2 },
  { id: 5, name: '钱七', department: '巡检二组', currentScore: 82, change: 4 },
  { id: 6, name: '孙八', department: '巡检三组', currentScore: 78, change: 6 }
])

// 积分获取记录
const scoreRecords = ref([
  { id: 1, memberName: '张三', action: '完成巡检任务', location: '东区停车场', score: 10, time: '2023-06-15 09:30:00' },
  { id: 2, memberName: '李四', action: '处理车辆违停', location: '西区商业街', score: 8, time: '2023-06-15 10:15:00' },
  { id: 3, memberName: '王五', action: '巡检点漏检', location: '南区公园', score: -5, time: '2023-06-15 11:20:00' },
  { id: 4, memberName: '赵六', action: '协助处理紧急事件', location: '北区住宅区', score: 15, time: '2023-06-15 13:45:00' },
  { id: 5, memberName: '钱七', action: '巡检延迟', location: '中心广场', score: -3, time: '2023-06-15 15:30:00' }
])

// 计算属性
const isEmpty = computed(() => {
  return memberScores.value.length === 0
})

// 方法
const onMonthChange = (e) => {
  selectedMonth.value = e.detail.value
  loadPerformanceData()
}

const formatMonth = (month) => {
  if (!month) return '请选择月份'
  const d = new Date(month + '-01')
  return `${d.getFullYear()}年${String(d.getMonth() + 1).padStart(2, '0')}月`
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const d = new Date(dateTime)
  return `${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}

const refreshPerformanceChart = () => {
  // 模拟刷新绩效图表数据
  const newData = {
    categories: ['第1周', '第2周', '第3周', '第4周'],
    series: [{
      name: '平均积分',
      data: Array.from({length: 4}, () => Math.floor(Math.random() * 20) + 70)
    }, {
      name: '完成任务数',
      data: Array.from({length: 4}, () => Math.floor(Math.random() * 20) + 40)
    }]
  }
  performanceChartData.value = newData
  uni.showToast({
    title: '绩效图表已刷新',
    icon: 'success'
  })
}

const getRankClass = (index) => {
  if (index === 0) return 'rank-first'
  if (index === 1) return 'rank-second'
  if (index === 2) return 'rank-third'
  return 'rank-normal'
}

const viewMemberDetail = (member) => {
  uni.showModal({
    title: '组员详情',
    content: `姓名：${member.name}\n部门：${member.department}\n当前积分：${member.currentScore}\n积分变化：${member.change >= 0 ? '+' : ''}${member.change}`,
    showCancel: false
  })
}

const viewScoreDetail = (record) => {
  uni.showModal({
    title: '积分详情',
    content: `组员：${record.memberName}\n行为：${record.action}\n地点：${record.location}\n积分：${record.score > 0 ? '+' : ''}${record.score}\n时间：${record.time}`,
    showCancel: false
  })
}

const showScoreFilter = () => {
  uni.showActionSheet({
    itemList: ['全部记录', '正积分', '负积分', '本周记录', '本月记录'],
    success: (res) => {
      console.log('选择了第' + (res.tapIndex + 1) + '个选项')
      // 这里可以根据选择的选项过滤积分记录
    }
  })
}

const loadPerformanceData = async () => {
  loading.value = true
  try {
    // 模拟加载绩效数据
    await new Promise(resolve => setTimeout(resolve, 500))
    // 根据selectedMonth加载对应月份的绩效数据
    console.log('加载绩效数据:', selectedMonth.value)
  } catch (error) {
    console.error('加载绩效数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  loadPerformanceData()
})
</script>

<style lang="scss" scoped>
.patrol-performance-container {
  padding: 30rpx;
  min-height: 100vh;
  background-color: #F5F5F5;
}

.page-header {
  margin-bottom: 30rpx;
  
  .header-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
  }
}

.month-selector {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  
  .selector-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .selector-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
    
    .month-picker {
      color: #1890ff;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      
      .arrow-icon {
        width: 24rpx;
        height: 24rpx;
        margin-left: 8rpx;
      }
    }
  }
}

.performance-metrics {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
  margin-bottom: 30rpx;
  
  .metric-card {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .metric-value {
      font-size: 48rpx;
      font-weight: 600;
      color: #1890ff;
      margin-bottom: 10rpx;
    }
    
    .metric-label {
      font-size: 26rpx;
      color: #666;
      margin-bottom: 8rpx;
    }
    
    .metric-change {
      font-size: 24rpx;
      
      &.positive {
        color: #52c41a;
      }
      
      &.negative {
        color: #ff4d4f;
      }
    }
  }
}

.performance-chart {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  
  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .chart-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
    
    .refresh-btn {
      background-color: #f0f9ff;
      color: #1890ff;
      border: 1rpx solid #d1ecf1;
      border-radius: 8rpx;
      padding: 12rpx 24rpx;
      font-size: 24rpx;
      line-height: 1;
    }
  }
  
  .chart-content {
    height: 400rpx;
  }
}

.member-ranking {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  
  .ranking-header {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 30rpx;
    display: block;
  }
  
  .member-list {
    .member-item {
      display: flex;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .rank-badge {
        width: 60rpx;
        height: 60rpx;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24rpx;
        font-weight: 600;
        margin-right: 20rpx;
        
        &.rank-first {
          background-color: #ffd700;
          color: #fff;
        }
        
        &.rank-second {
          background-color: #c0c0c0;
          color: #fff;
        }
        
        &.rank-third {
          background-color: #cd7f32;
          color: #fff;
        }
        
        &.rank-normal {
          background-color: #f5f5f5;
          color: #666;
        }
      }
      
      .member-info {
        flex: 1;
        
        .member-name {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 8rpx;
          display: block;
        }
        
        .member-dept {
          font-size: 24rpx;
          color: #999;
          display: block;
        }
      }
      
      .member-score {
        text-align: right;
        
        .current-score {
          font-size: 32rpx;
          font-weight: 600;
          color: #1890ff;
          margin-bottom: 4rpx;
          display: block;
        }
        
        .score-change {
          font-size: 22rpx;
          display: block;
          
          &.positive {
            color: #52c41a;
          }
          
          &.negative {
            color: #ff4d4f;
          }
        }
      }
    }
  }
}

.score-records {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  
  .records-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .records-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
    
    .filter-btn {
      background-color: #f0f9ff;
      color: #1890ff;
      border: 1rpx solid #d1ecf1;
      border-radius: 8rpx;
      padding: 12rpx 24rpx;
      font-size: 24rpx;
      line-height: 1;
    }
  }
  
  .record-list {
    .record-item {
      display: flex;
      align-items: center;
      padding: 24rpx 0;
      border-bottom: 1rpx solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .record-info {
        flex: 1;
        
        .record-action {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 8rpx;
          display: block;
        }
        
        .record-details {
          font-size: 24rpx;
          color: #999;
          
          .record-member {
            margin-right: 20rpx;
          }
          
          .record-location {
            margin-right: 20rpx;
          }
        }
      }
      
      .record-score {
        text-align: right;
        
        .score-value {
          font-size: 32rpx;
          font-weight: 600;
          margin-bottom: 4rpx;
          display: block;
          
          &.positive {
            color: #52c41a;
          }
          
          &.negative {
            color: #ff4d4f;
          }
        }
        
        .record-time {
          font-size: 22rpx;
          color: #999;
          display: block;
        }
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  
  .empty-icon {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 30rpx;
    opacity: 0.3;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 60rpx;
  
  text {
    font-size: 28rpx;
    color: #666;
  }
}
</style>